<template>
  <div class="bg-light min-vh-100 d-flex flex-column">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link :to="`/english/weekTestExam?noticeId=${noticeId}&examPaperId=${examPaperId}`" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">大作文</h5>
    </div>

    <!-- 写作任务卡片 -->
    <div class="writing-card flex-grow-1">
      <div class="task-info mb-3">
        <h6 class="mb-2">&nbsp;&nbsp;{{ subjectName }}&nbsp;&nbsp;大作文题目</h6>
        <p class="text-muted article-text">
          {{article}}
        </p>
        <!-- 图片区域 -->
        <div class="picture-area mb-3">
        <img :src="pictureUrl" alt="题目图片" class="img-fluid rounded">
        </div>
<!--        <ol class="text-muted">-->
<!--          <li>describe the picture briefly,</li>-->
<!--          <li>explain its intended meaning, and</li>-->
<!--          <li>give your comments.</li>-->
<!--        </ol>-->
      </div>

      <!-- 写作区域 -->
      <div class="writing-area">
        <textarea
          v-model="userAnswer"
          class="form-control"
          rows="12"
          placeholder="在此输入你的答案..."
        ></textarea>
        <div class="word-count text-end mt-2">
          字数：{{ wordCount }} / 200
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <div class="action-buttons">
        <button class="btn btn-primary" @click="submitAnswers">
          提交答案
        </button>
      </div>
    </div>

    <!-- 范文弹窗 -->
    <div class="modal fade" id="sampleAnswerModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">参考范文</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <p>The picture shows a young person sitting at a desk, surrounded by various electronic devices including a smartphone, a tablet, and a laptop. While these modern gadgets are meant to enhance efficiency, the person appears overwhelmed and distracted.</p>
            <p>This image intends to illustrate the double-edged nature of modern technology. While digital devices can boost productivity and connectivity, they can also lead to information overload and decreased focus. The person's posture and expression suggest mental fatigue from constant digital stimulation.</p>
            <p>In my opinion, this phenomenon reflects a common challenge in today's digital age. While technology brings unprecedented convenience, we must learn to manage it wisely. Setting boundaries for device usage, practicing digital detox, and maintaining a healthy balance between online and offline activities are essential for our mental well-being and productivity.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Modal } from 'bootstrap'
import http from "@/router/http";
import router from "@/router";
import {moduleTypeDict} from "@/router/dict";

export default {
  name: 'LargeWritingView',
  data() {
    return {
      userAnswer: '',
      noticeId: this.$route.query.noticeId,
      modal: null,
      selectYear: null,
      startTime: 0, // 记录答题开始时间（毫秒数）
      totalTimeSpent: 0, // 累计答题时间（毫秒数）
      subjectName: '',
      article: '',
      examPaperId: '',
      questionId: '',
      userAnswers: [],
      pictureUrl: ''
    }
  },
  computed: {
    wordCount() {
      return this.userAnswer.trim().split(/\s+/).length
    }
  },
  mounted() {
    this.modal = new Modal(document.getElementById('sampleAnswerModal'))
    this.examPaperId = this.$route.query.examPaperId;
    this.noticeId = this.$route.query.noticeId;
    this.startTime = Date.now(); // 记录答题开始时间（毫秒数）
    this.fetchDataFromBackend();
  },
  methods: {
    showSampleAnswer() {
      this.modal.show()
    },
    async fetchDataFromBackend() {
      try {
        const moduleType = moduleTypeDict.find(item => item.code === 'dzw').name;
        const params = {
          examPaperId: this.examPaperId,
          subjectName: 'english',
          moduleType: moduleType,
          currentQuestionIndex: 1
        }
        const response = await http.get('/student/question/getQuestionInfoForEnglish', {params: params});
        const data = response.data;
        if (data && data.code === 1 && data.response) {
          this.examPaperId = data.response.examPaperId;
          this.questionId = data.response.questionId;
          this.article = data.response.article;
          this.subjectName = data.response.subjectName;
          this.pictureUrl = data.response.pictureUrl;
        } else {
          alert("暂无数据，请稍后再试");
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
        }
      } catch (error) {
        console.error('获取阅读数据失败:', error);
      }
    },
    async submitAnswers() {
      try {
        const currentTime = Date.now(); // 获取当前时间（毫秒数）
        this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
        this.userAnswers.push({
          index: 0,
          value: this.userAnswer.trim(),
        })
        const submitParentData = {
          questionId: this.questionId,
          examPaperId: this.examPaperId,
          totalTimeSpent: this.totalTimeSpent,
          resource: 1,
          userAnswer: this.userAnswers,
          isTest: true
        }

        // 发送POST请求将答题数据提交到后端
        const response = await http.post('/student/answer/submitAnswerForEnglish', submitParentData);
        if (response.status === 200) {
          alert('答题数据提交成功');
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
          // 可以根据业务需求进行其他操作，比如提示用户提交成功，跳转到特定页面等
        } else {
          console.error('答题数据提交失败');
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
          // 同样可根据业务需求进行相应提示等操作
        }
      } catch (error) {
        console.error('提交答题数据出现错误:', error);
      }
    }
  }
}
</script>

<style scoped>
.article-text {
  white-space: pre-line; /* 让文本中的换行符生效，实现自动换行 */
}
.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.writing-card {
  background: white;
  margin: 15px;
  margin-bottom: 80px;
  padding: 20px;
  border-radius: 15px;
  overflow-y: auto;
}

.task-info {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.picture-area {
  max-width: 100%;
  text-align: center;
}

.picture-area img {
  max-width: 100%;
  height: auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.writing-area textarea {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  font-size: 16px;
  resize: none;
}

.word-count {
  color: #666;
  font-size: 14px;
}

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

ol {
  padding-left: 1.2rem;
}

ol li {
  margin-bottom: 0.5rem;
}
</style> 